﻿using _111.QywxDocument.MeiTuanComment.Model;
using guidHelper;
using MyDapperApi.Services.QywxBase;
using QYWXUpdate.DataModel;
using QYWXUpdate.DataModel.QYWXDocument;
using static MyDapperApi.Services.DateBaseService;

namespace MyDapperApi.Services.QywxDocument.MeiTuanComment;
public class DocMeiTuanCommentService : IDocMeiTuanCommentService
{
    private readonly IConfiguration _configuration;
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly IDateBaseService _dateBaseService;
    private readonly IQywxBaseService _qywxBaseService;
    public readonly ICsvService _csvService;
    private readonly string _qywxReceiveToken = "sdas";
    private readonly string _corpId;
    private readonly INetDocumentService _netDocumentService;

    // 通过依赖注入获取配置，从而读取连接字符串
    public DocMeiTuanCommentService(IHttpClientFactory httpClientFactory,
        IConfiguration configuration,
        IDateBaseService dateBaseService,
        ICsvService csvService,
        IQywxBaseService qywxBaseService,
        INetDocumentService netDocumentService)
    {
        _configuration = configuration;
        _httpClientFactory = httpClientFactory;
        _dateBaseService = dateBaseService;
        _csvService = csvService;
        _corpId = configuration["QywxSettings:CorpId"];
        _qywxBaseService = qywxBaseService;
        _netDocumentService = netDocumentService;
    }

    #region 美团差评创建表格

    public async Task<CommonResponse> LoopTempInsertMeiTuanComment()//
    {
        var result = new CommonResponse();

        // 起始日期：2025-10-01 00:00:00.
        DateTime startDate = DateTime.ParseExact("2025-10-23 00:00:00", "yyyy-MM-dd HH:mm:ss", null);
        // 结束日期：2025-10-23 00:00:00
        DateTime endDate = DateTime.ParseExact("2025-10-23 00:00:00", "yyyy-MM-dd HH:mm:ss", null);

        // 计算总天数（包含起止日期，共23天）
        int totalDays = (int)(endDate - startDate).TotalDays + 1;

        for (int i = 0; i < totalDays; i++)
        {
            // 每天的00:00:00（在起始日期基础上累加i天）
            DateTime currentDate = startDate.AddDays(i).Date; // .Date确保时间为00:00:00
            result = await InsertMeiTuanComment(currentDate);
        }

        return result;
    }

    public async Task<CommonResponse> InsertMeiTuanComment(DateTime dateTime)
    {
        var result = new CommonResponse();

        var startTime = dateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");
        var endTime = dateTime.AddDays(1).Date.ToString("yyyy-MM-dd HH:mm:ss");

        var sqlbuilder = new SqlBuilder();
        var sql = @$"SELECT 
  shop_name AS `ShopName`,
  user_nick_name AS `UserNickName`,
  add_time AS `AddTime`,
  star,
  mc.content,
  consumer_item AS `ConsumerItem`,
  consumer_date AS `ConsumerDate`,
  consumer_amount AS `ConsumerAmount`,
  CASE WHEN platform = 0 THEN '点评' ELSE '美团' END AS `Platform`,
  oc.content AS `AIContent`
FROM mt_comment mc
LEFT JOIN openai_content oc ON mc.review_id = oc.comment_id
WHERE add_time > '{startTime}' and add_time < '{endTime}'
 ";

        var entity = await _dateBaseService.QueryAsync<CommentMsgModel>(sql, sqlbuilder, 0, "PlatInformationConnection");

        var documentRequest = new InsertDocumentRequest<QywxDocumentMeiTuanMsg>()
        {
            docid = "dcl1Ean315JR0ATof4Jmrhb1UUyyEFhv3kXBFyHnZ-8OfEo4iXVhnln_B-nrqVsOSXqA6bv0efFrY1hIP9VxddiQ",
            sheet_id = "q979lj",
            key_type = "CELL_VALUE_KEY_TYPE_FIELD_ID",
            records = new List<InsertDocumentRecords<QywxDocumentMeiTuanMsg>>()
        };

        foreach (var item in entity)
        {
            var temp = new QywxDocumentMeiTuanMsg()
            {
                ftIFXS = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = item.ConsumerItem ?? string.Empty } },
                f04Gwj = new List<InsertDocumentCommonSelectType>() { new InsertDocumentCommonSelectType { type = "text", id = GetShopId(item.ShopName) ?? string.Empty } },
                fFKi1F = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = item.Star ?? string.Empty } },
                fUxGvY = ToolHelper.ConvertDateTimeStringToMilliseconds(item.AddTime) ?? string.Empty,
                fVgHZQ = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = item.Platform ?? string.Empty } },
                fsAXTn = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = item.ConsumerAmount ?? string.Empty } },
                f0Yso5 = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = item.Content ?? string.Empty } },
                fU5RAJ = ToolHelper.ConvertDateTimeStringToMilliseconds(item.ConsumerDate) ?? string.Empty,
                ftk5Tx = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = item.UserNickName ?? string.Empty } },
                fx4Oz1 = new List<InsertDocumentCommonTextType>() { new InsertDocumentCommonTextType { type = "text", text = item.AIContent ?? string.Empty } },
            };
            var temp1 = new InsertDocumentRecords<QywxDocumentMeiTuanMsg>()
            {
                values = temp
            };
            documentRequest.records.Add(temp1);
        }

        result = await _netDocumentService.InsertDocument<QywxDocumentMeiTuanMsg>(documentRequest);

        return result;
    }

    public string GetShopId(string request)
    {
        var res = string.Empty;
        switch (request)
        {
            case "曲水兰亭(武汉光谷店)":
                res = "oRsTOn";
                break;
            case "曲水兰亭(北京四惠店)":
                res = "oftf3l";
                break;
            case "曲水兰亭(上海虹桥店)":
                res = "o6g9Oz";
                break;
            case "曲水兰亭(苏州金鸡湖店)":
                res = "omCAfw";
                break;
            case "曲水兰亭(武汉徐东店)":
                res = "oLbEkS";
                break;
            case "曲水兰亭(杭州城东店)":
                res = "oXJFSY";
                break;
            case "水裹·汤泉生活(龙湖虹桥天街店)":
                res = "oqaEso";
                break;
            case "水裹·汤泉(五角场店)":
                res = "ouw0bB";
                break;
            case "水裹·汤泉(桃源国际店)":
                res = "ocul5Q";
                break;
            case "水裹·汤泉(钱江世纪公园店)":
                res = "oMmuos";
                break;
            case "水裹+(合生汇店)":
                res = "oiVWo2";
                break;
            case "水裹·汤泉生活(新天地店)":
                res = "oQWKQ2";
                break;
            case "水裹·汤泉(四惠店)":
                res = "oZl2Wy";
                break;
            case "水裹·汤泉生活馆(常青里店)":
                res = "ovkXm4";
                break;
            // 若有未匹配的情况，默认返回空（可根据需求调整，如抛出异常）
            default:
                res = string.Empty;
                break;
        }
        return res;
    }

    #endregion
}